import { TextDecoder } from 'text-encoding-utf-8';
let bluetoothOpen = false; // 手机蓝牙是否打开
let bluetoothConnect = false; // 设备和蓝牙是否连接
let isHaveDevice = false; // 是否查找到设备
let deviceId = null; // 设备id
let serviceId = null; // 服务id
let notify = null; // 监听uuid
let writeId = null; // 写入uuid
let write_uuid_key_id = null; // 写入写秘钥的uuid
/**
 * 获取手机蓝牙是否打开
 */
const getBluetoothState = () => {
	// 主机模式
	return new Promise((resolve, reject) => {
		uni.openBluetoothAdapter({
			success: (r) => {
				console.log("蓝牙初始化成功");
				// 获取蓝牙的匹配状态
				uni.getBluetoothAdapterState({
					success: function(row) {
						console.log('蓝牙状态：', row.available);
						if (row.available) {
							bluetoothOpen = true;
							resolve();
						} else {
							// 请开启蓝牙
							bluetoothOpen = false;
							bluetoothConnect = false;
							reject();
						}
					},
					fail: function(err) {
						// 请开启蓝牙
						bluetoothOpen = false;
						bluetoothConnect = false;
						reject();
					}
				})
			},
			fail: () => {
				// 请开启蓝牙
				bluetoothOpen = false;
				bluetoothConnect = false;
				reject();
			}
		});
	});
};
/**
 * 开始搜索蓝牙设备
 */
const discoveryBluetooth = () => {
	return new Promise((resolve) => {
		uni.startBluetoothDevicesDiscovery({
			success(res) {
				console.log('搜索蓝牙外围设备完成', res)
				setTimeout(() => {
					resolve();
				}, 2000);
			}
		});
	})
};
// 关闭蓝牙搜索
const stopDiscoveryBluetooth = () => {
	uni.stopBluetoothDevicesDiscovery({
		success(r) {
			console.log("停止搜索蓝牙设备", r);
		}
	});
};
/**
 * 获取搜索到的设备信息
 */
const getBluetoothDevices = () => {
	return new Promise((resolve, reject) => {
		uni.getBluetoothDevices({
			success(res) {
				console.log("获取蓝牙设备", res);
				bluetoothConnect = false;
				// 过滤掉name为空或者未知设备的设备
				let devices = res.devices.filter(function(obj) {
					return obj.name !== "" && obj.name !== "未知设备"
				});
				devices && devices.forEach(item => {
					// ED719W_34b7daf7f57d
					// 判断设备开头是不是ED，并且分割_字符串，判断后面的是不是跟设备编码一致
                    if (item.name && item.name.startsWith('ED')) {
						// console.log("111111", item.name);
                        let deviceCode = item.name.split('_')[1]; // 假设设备编码在"_"之后
						// console.log("2222222", deviceCode);
                        // 假设我们有一个预定义的设备编码
                        let predefinedDeviceCode = uni.getStorageSync('mac_code') || '';
                        if (deviceCode === predefinedDeviceCode) {
                            deviceId = item.deviceId;
                        }
                    }
				});
			},
			fail: function(err) {
				console.log('搜索蓝牙设备失败',err);
				bluetoothConnect = false;
				reject();
			},
			complete: function() {
				console.log("蓝牙搜索完成", deviceId);
				// 是否具有当前设备
				if (deviceId) {
					console.log("获取到设备id", deviceId);
					isHaveDevice = true;
				} else {
					isHaveDevice = false;
				}
				resolve(isHaveDevice);
			}
		});
	});
}
/**
 * 连接蓝牙
 * deviceId 蓝牙设备id
 * 连接蓝牙
 * deviceId 蓝牙设备id
 */
const connectBluetooth = () => {
	return new Promise((resolve, reject) => {
		console.log("bluetoothConnect", bluetoothConnect);
		console.log("deviceId", deviceId);
		// 检查是否已连接
		if (bluetoothConnect && deviceId) {
			console.log("设备已连接，无需重复连接");
			resolve();
			return;
		}
		
		uni.createBLEConnection({
			deviceId: deviceId, // 设备id
			success() {
				bluetoothConnect = true;
				console.log("蓝牙连接成功",bluetoothConnect);
				// 蓝牙连接成功后关闭蓝牙搜索
				stopDiscoveryBluetooth();
				resolve();
				// 获取服务id
				getServiceId();
			},
			fail(err) {
				bluetoothConnect = false;
				console.log("蓝牙连接失败",err);
				reject();
			}
		});
	});
};
	// 获取服务id
const getServiceId = () => {
	uni.getBLEDeviceServices({
		deviceId: deviceId,
		success(res) {
			console.log("获取服务Id", res)
			let model = res.services[0];
			serviceId = model.uuid;
			// 调用蓝牙监听和写入功能
			getCharacteId();
		}
	})
};
/* 接收到的数据
 {"services": [
		{"uuid": "000000F4-0000-1000-8000-00805F9B34FB", "isPrimary": true}, 
		{"uuid": "00001801-0000-1000-8000-00805F9B34FB", "isPrimary": true}, 
		{"uuid": "00001800-0000-1000-8000-00805F9B34FB", "isPrimary": true}
	], 
	"errCode": 0, 
	"errno": 0, 
	"errMsg": "getBLEDeviceServices:ok"
} */

// 获取蓝牙低功耗设备某个服务中所有特征
const getCharacteId = () => {
	uni.getBLEDeviceCharacteristics({
		deviceId: deviceId, // 蓝牙设备id
		serviceId: serviceId, // 蓝牙服务UUID
		success(res) {
			console.log('数据监听', res);
			
			// 1. 先订阅通知(F301)
			const notifyChar = res.characteristics.find(item => 
				item.properties.notify === true && 
				item.uuid.split('-')[0] === '0000F301'
			);
			
			if (notifyChar) {
				notify = notifyChar.uuid;
				startNotice().then(() => {
					// 2. 订阅成功后写入密钥(F402)
					const keyChar = res.characteristics.find(item => 
						item.properties.write === true && 
						item.uuid.split('-')[0] === '0000F402'
					);
					
					if (keyChar) {
						const write_uuid_key_id = keyChar.uuid;
						uni.setStorageSync("write_uuid_key_id", write_uuid_key_id);
						const hexString = uni.getStorageSync('mac_code') + '0000'; // MAC地址+0000
						const buffer = buildBleData(hexString);
						console.log("写入数据秘钥", buffer);
						writeData(buffer, write_uuid_key_id).then(() => {
							// 3. 密钥写入成功后写入账号密码(F401)
							const wifiChar = res.characteristics.find(item => 
								item.properties.write === true && 
								item.uuid.split('-')[0] === '0000F401'
							);
							
							if (wifiChar) {
								const writeId = wifiChar.uuid;
								uni.setStorageSync("writeId", writeId);
								const wifiName = uni.getStorageSync("wifiName");
								const wifiPassword = uni.getStorageSync("wifiPassword");
								
								if (!wifiName || !wifiPassword) {
									uni.showToast({ title: '未获取到WIFI名称或密码', icon: 'none' });
									return;
								}
								
								const credentials = `${wifiName}|${wifiPassword}`;
								const buffer = buildBleData(credentials);
								console.log("写入数据账号密码", buffer);
								writeData(buffer, writeId);
							}
						});
					}
				});
			}
		},
		fail(err) {
			console.log("数据监听失败", err)
		}
	})
};
/* 接收到的数据
{"characteristics": [
	{
		"uuid": "0000F401-0000-1000-8000-00805F9B34FB", 
		"handle": 42, 
		"properties": {
			"read": false, 
			"write": true, 
			"notify": false, 
			"indicate": false, 
			"writeNoResponse": false, 
			"writeDefault": true
		}
	}, 
	{
		"uuid": "0000F402-0000-1000-8000-00805F9B34FB", 
		"handle": 44, 
		"properties": {
			"read": false, 
			"write": true, 
			"notify": false, 
			"indicate": false, 
			"writeNoResponse": false, 
			"writeDefault": true
		}
	}, 
	{
		"uuid": "0000F403-0000-1000-8000-00805F9B34FB", 
		"handle": 46, 
		"properties": {
			"read": false, 
			"write": true, 
			"notify": false, 
			"indicate": false,
			"writeNoResponse": false, 
			"writeDefault": true
		}
	}, {
		"uuid": "0000F301-0000-1000-8000-00805F9B34FB", 
		"handle": 48, 
		"properties": {
			"read": false, 
			"write": false, 
			"notify": true, 
			"indicate": false, 
			"writeNoResponse": false, 
			"writeDefault": false
		}
	}, {
		"uuid": "0000F302-0000-1000-8000-00805F9B34FB", 
		"handle": 51, 
		"properties": {
			"read": false, 
			"write": false, 
			"notify": true, 
			"indicate": false,
			 "writeNoResponse": false, 
			 "writeDefault": false
		}
	}, {
		"uuid": "0000F303-0000-1000-8000-00805F9B34FB", 
		"handle": 54, 
		"properties": {
			"read": false, 
			"write": false, 
			"notify": true, 
			"indicate": false, 
			"writeNoResponse": false, 
			"writeDefault": false
		}
	}, {
		"uuid": "0000F501-0000-1000-8000-00805F9B34FB", 
		"handle": 57, 
		"properties": {
			"read": true, 
			"write": false, 
			"notify": false, 
			"indicate": false, 
			"writeNoResponse": false, 
			"writeDefault": false
		}
	}, {
	"uuid": "0000F7CD-0000-1000-8000-00805F9B34FB", 
	"handle": 59, 
	"properties": {
		"read": true, 
		"write": true,
		 "notify": true, 
		 "indicate": false, 
		 "writeNoResponse": false,
		  "writeDefault": true
	}}
], 
"errCode": 0, 
"errno": 0, 
"errMsg": "getBLEDeviceCharacteristics:ok"
} */

// 启用低功耗蓝牙设备特征值变化时的notify功能
const startNotice = () => {
	var that = this;
	return new Promise((resolve, reject) => {
		console.log("启用低功耗蓝牙设备特征值变化时的notify功能");
		uni.notifyBLECharacteristicValueChange({
			characteristicId: notify,
			deviceId: deviceId,
			serviceId: serviceId,
			state: true,
			success(res) {
				console.log("启用低功耗蓝牙设备特征值变化时的notify功能", res);
				// 监听低功耗蓝牙设备的特征值变化
				uni.onBLECharacteristicValueChange(result => {
					console.log("监听低功耗蓝牙设备的特征值变化", result);
					if (result.value) {
						console.log("解析状态值",ab2hex(result.value))
						const data = ab2hex(result.value);
			
						
						// 解析状态值
						try {
							const stateValue = parseInt(data);
							switch(stateValue) {
								case 1:
									uni.showToast({ title: 'WIFI名或密码格式错误', icon: 'none' });
									break;
								case 2:
									uni.showToast({ title: 'WIFI连接失败', icon: 'none' });
									that.showOverlay = false;
									break;
								case 3:
									// uni.showToast({ title: 'WIFI连接成功', icon: 'success' });
									uni.redirectTo({ 
										url: '/otherpages/health/equipment'
									});
									// 增加断开蓝牙处理
									closeBluetoothConnection();
									break;
								case 4:
									// uni.showToast({ title: 'WIFI连接中，请等待...', icon: 'loading' });
									break;
								case 5:
									// uni.showToast({ title: '设备绑定成功', icon: 'success' });
									break;
								case 6:
									uni.showToast({ title: '设备绑定失败', icon: 'none' });
									break;
								case 7:
									// uni.showToast({ title: '密钥匹配成功', icon: 'success' });
									break;
								case 8:
									uni.showToast({ title: '密钥匹配失败', icon: 'none' });
									break;
								default:
									console.log('未知状态值:', stateValue);
							}
						} catch (e) {
							console.error('状态值解析错误:', e);
						}
					}
				});
				resolve();
			},
			fail(err) {
				console.log("启用通知失败", err);
				reject(err);
			}
		});
	});
};
// 断开低功耗蓝牙设备
const closeBluetoothConnection = () => {
	uni.closeBLEConnection({
		deviceId: deviceId,
		success(r) {
			console.log("断开低功耗蓝牙设备", r);
		}
	})
};
// 蓝牙发送数据
const writeData = (buffer,writeId) => {
	return new Promise((resolve, reject) => {
		uni.writeBLECharacteristicValue({
			characteristicId: writeId,
			deviceId: deviceId,
			serviceId: serviceId,
			value: buffer,
			success(res) {
				console.log("writeBLECharacteristicValue success", res);
				resolve();
			},
			fail(err) {
				console.log("报错了", err);
				reject();
			}
		});
	});
};

//数据转换
// 该函数接收一个字符串str作为参数，并调用其他两个函数来将该字符串转换为特定格式的ArrayBuffer。
function buildBleData(str) {
	return arr2formatArrayBuffer(str2utf8Arr(str))
}

// 该函数接收一个字符串str作为参数，并将其转换为UTF-8编码的数值数组
function str2utf8Arr (str) {
	let arr = []
	str = encodeURI(str)
	let i = 0
	for (; i < str.length; i++) {
	  let utf8Val
	  if (str[i] === '%') {
		i++
		utf8Val = parseInt(str.slice(i, i+2), 16)
		i++
	  } else {
		utf8Val = str.charCodeAt(i)
	  }
	  arr.push(utf8Val)
	}
	return arr
  }
  
//   该函数接收一个数值数组arr作为参数，并将其转换为特定格式的ArrayBuffer
  function arr2formatArrayBuffer(arr) {
	const unitDataLen = 18
	const unitHeadLen = 2
	const unitLen = unitHeadLen + unitDataLen
	let dataLen = arr.length
	let unitNum = Math.ceil(dataLen/unitDataLen)
	let buffer = new ArrayBuffer(dataLen + unitNum * unitHeadLen)
	let dataView = new DataView(buffer)
	for (let i = 0; i < unitNum; i++) {
	  let unitdata = arr.slice(i * unitDataLen, (i + 1) * unitDataLen)
	  dataView.setUint8(i * unitLen, 0xa7)
	  dataView.setUint8(i * unitLen + 1, (unitNum << 4) | (i+1))
	  for (let j = 0; j < unitdata.length; j++) {
		dataView.setUint8(i * unitLen + 2 + j, unitdata[j])
	  }
	}
	return buffer
}

function ab2hex(buffer) {
	const hexArr = Array.prototype.map.call(
	  new Uint8Array(buffer),
	  function (bit) {
		return ('00' + bit.toString(16)).slice(-2)
	  }
	)
	return hexArr.join('')
}

export default {
	getBluetoothState,
	discoveryBluetooth,
	stopDiscoveryBluetooth,
	getBluetoothDevices,
	connectBluetooth,
	getServiceId,
	getCharacteId,
	startNotice,
	closeBluetoothConnection,
	writeData,
	buildBleData,
	str2utf8Arr,
	arr2formatArrayBuffer
};
